<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<avue-crud
				ref="crud"
				v-model="form"
				:option="option"
				:data="data"
				:page="page"
				@on-load="getList"
				@search-change="searchFilter"
				@row-save="handleSave"
				@row-update="handleUpdate"
				@row-del="rowDel"
				:before-open="handleOpenBefore"
				@size-change="sizeChange"
				@current-change="currentChange"
				:table-loading="tableLoading"
			>
				<template #unitNo-form>
					<avue-select
						placeholder="请选择 设备名称"
						@change="devChange"
						filterable
						:dic="devData"
						:props="devDataProps"
						v-model="form.unitNo"
						:disabled="editDisabled"
					></avue-select>
				</template>
				<template #devCategory-form>
					<avue-select
						placeholder="请选择 品类"
						@change="categoryChange"
						filterable
						:dic="categoryData"
						:props="categoryDataProps"
						v-model="form.devCategory"
						:disabled="editDisabled"
					></avue-select>
				</template>
				<template #devModel-form>
					<avue-select
						placeholder="请选择 产品"
						@change="productChange"
						filterable
						:dic="productData"
						:props="productDataProps"
						v-model="form.devModel"
						:disabled="editDisabled"
					></avue-select>
				</template>
				<template #ratedPower-form>
					<avue-input-number :min="0" v-model="form.ratedPower"></avue-input-number>
				</template>
				<template #menu-left="{}">
					<el-button type="primary" @click="open">批量新增 </el-button>
					<!-- <el-button type="primary" @click="$refs.excelUpload.show()">批量导入 </el-button> -->
				</template>
			</avue-crud>

			<el-dialog title="批量新增" v-model="showDialog" width="50%">
				<el-form :model="batchForm" :rules="batchRules" ref="batchForm" label-width="100px">
					<el-row>
						<el-col :span="10">
							<el-form-item label="计量类型:" prop="energyType">
								<el-select v-model="batchForm.energyType" placeholder="请选择计量类型" style="width: 98%">
									<el-option v-for="a in energyTypeDic" :key="a.value" :label="a.label" :value="a.value"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="10" :offset="4">
							<el-form-item label="所属品类:" prop="devCategory">
								<el-select v-model="batchForm.devCategory" placeholder="请选择品类" style="width: 98%" @change="categoryChange2">
									<el-option v-for="a in categoryData" :key="a.identify" :label="a.name" :value="a.identify" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="10">
							<el-form-item label="所属产品:" prop="devModel">
								<el-select v-model="batchForm.devModel" placeholder="请选择产品" style="width: 98%" @change="productChange2">
									<el-option v-for="a in productData" :key="a.productKey" :label="a.name" :value="a.productKey" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="10" :offset="4">
							<el-form-item label="额定功率:" prop="ratedPower" v-if="batchForm.energyType == '1'" style="width: 98%">
								<el-input-number :min="0" v-model="batchForm.ratedPower"></el-input-number>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row>
						<el-transfer
							style="width: 100%; text-align: center"
							:titles="['未注册设备列表', '选中设备列表']"
							filterable
							:filter-method="filterMethod"
							v-model="batchData"
							:data="devData2"
						></el-transfer>
					</el-row>
				</el-form>
				<div style="margin-top: 10px; display: flex; justify-content: end">
					<span slot="footer" class="dialog-footer">
						<el-button @click="showDialog = false">取 消</el-button>
						<el-button type="primary" @click="save">保 存</el-button>
					</span>
				</div>
			</el-dialog>
			<!--excel 模板导入 -->

			<upload-excel
				ref="excelUpload"
				url="/bum/regdev/import"
				temp-url="/bm/sys-file/local/energydeviceregistytemplate.xlsx"
				title="设备注册批量导入"
				@refreshDataList="refreshChange"
			></upload-excel>
		</div>
	</div>
</template>
<script>
import {
	getDevList,
	addDevList,
	delDevList,
	getUnRegisterDevList,
	editDevList,
	batchAddDevList,
	getEnergyType,
} from '/@/api/consumptionmanagement/register/device';
import { fetchList as getCategoryList } from '/@/api/basiciot/device/category';
import { fetchList as getProductList } from '/@/api/basiciot/device/product';
import { fetchListNoPage as getUnDevList } from '/@/api/basiciot/device/device';
import { Session } from '/@/utils/storage';
import { useDict } from '/@/hooks/dict';

export default {
	data() {
		return {
			form: {},
			data: [],
			devData: [],
			devData2: [],
			unDevData: [],
			batchData: [],
			energyTypeDic: [],
			devDataProps: {
				label: 'deviceName',
				value: 'unitNo',
			},
			categoryData: [],
			categoryDataProps: {
				label: 'name',
				value: 'identify',
			},
			productData: [],
			productDataProps: {
				label: 'name',
				value: 'productKey',
			},
			editDisabled: false,
			page: {
				total: 0, // 总页数
				currentPage: 1, // 当前页数
				pageSize: 10, // 每页显示多少条
			},
			batchForm: {
				energyType: '',
				ratedPower: '',
				devModel: '',
				devCategory: '',
			},
			batchRules: {
				energyType: [{ required: true, message: '请选择计量类型', trigger: 'blur' }],
				devModel: [{ required: true, message: '请选择产品', trigger: 'blur' }],
				devCategory: [{ required: true, message: '请选择品类', trigger: 'blur' }],
			},
			tableLoading: false,
			showDialog: false,
			option: {
				index: false,
				searchMenuSpan: 10,
				labelWidth: 150,
				searchLabelWidth: 'auto',
				searchMenuPosition: 'left',
				addBtn: true,
				editBtn: true,
				delBtn: true,
				columnBtn: false,
				searchSpan: 6,
				refreshBtn: false,
				searchShowBtn: false,
				gridBtn: false,
				column: [
					{
						label: '能耗设备国家编码',
						type: 'input',
						prop: 'gbCode',
					},
					{
						label: '计量类型',
						prop: 'energyType',
						type: 'select',
						dicUrl: '/api/admin/dict/type/energy_type',
						dicHeaders: {
							authorization: 'Bearer ' + Session.get('token'),
						},
						props: {
							label: 'label',
							value: 'value',
						},
						editDisabled: true,
						rules: [
							{
								required: true,
								trigger: 'blur',
								message: '计量类型必填',
							},
						],
						control: (val, form) => {
							if (val != '1') {
								return {
									ratedPower: {
										display: false,
									},
								};
							} else {
								return {
									ratedPower: {
										display: true,
									},
								};
							}
						},
					},
					{
						label: '所属品类',
						prop: 'devCategory',
						type: 'select',
						overHidden: true,
						rules: [
							{
								required: true,
								trigger: 'blur',
								message: '所属品类必填',
							},
						],
						hide: true,
					},
					{
						label: '所属产品',
						prop: 'devModel',
						type: 'select',
						overHidden: true,
						rules: [
							{
								required: true,
								trigger: 'blur',
								message: '所属产品必填',
							},
						],
						hide: true,
					},
					{
						label: '设备名称',
						prop: 'deviceName',
						type: 'select',
						overHidden: true,
						addDisplay: false,
						editDisplay: false,
					},
					{
						label: '设备名称',
						prop: 'unitNo',
						type: 'select',
						overHidden: true,
						rules: [
							{
								required: true,
								trigger: 'blur',
								message: '设备名称必填',
							},
						],
						hide: true,
					},
					{
						type: 'input',
						label: '表计名称',
						prop: 'unitName',
						search: true,
						rules: [
							{
								required: true,
								trigger: 'blur',
								message: '表计名称必填',
							},
						],
					},
					{
						type: 'input',
						label: '额定功率',
						prop: 'ratedPower',
						hide: true,
					},
					{
						type: 'date',
						label: '创建时间',
						prop: 'createTime',
						addDisplay: false,
						editDisplay: false,
					},
					{
						type: 'input',
						label: '备注',
						prop: 'remark',
					},
				],
			},
		};
	},
	mounted() {
		getCategoryList({ current: 1, size: 999 }).then((res) => {
			this.categoryData = res.data.records;
		});
		getEnergyType().then((res) => {
			this.energyTypeDic = res.data;
		});
	},
	methods: {
		//品类切换事件
		categoryChange(val) {
			if (val.value) {
				getProductList({ current: 1, size: 999, category: val.value }).then((res) => {
					this.productData = res.data.records;
				});
			}
			if (!this.editDisabled) {
				this.form.devModel = '';
				this.form.unitNo = '';
				this.productData = [];
				this.devData = [];
			}
		},
		categoryChange2(val) {
			this.batchForm.devModel = '';
			this.devData2 = [];
			if (val) {
				getProductList({ current: 1, size: 999, category: val }).then((res) => {
					this.productData = res.data.records;
				});
			}
		},
		//产品切换事件
		productChange(val) {
			if (val.value) {
				getUnRegisterDevList({ devModel: val.value }).then((res) => {
					this.devData = res.data;
				});
			}
			if (!this.editDisabled) {
				this.form.unitNo = '';
				this.devData = [];
			}
		},
		productChange2(val) {
			this.queryUnRegisterDevList(val);
		},
		//设备切换事件
		devChange(val) {
			if (!this.editDisabled) {
				this.form.unitName = val?.item?.deviceName;
			}
		},
		sizeChange(pageSize) {
			this.page.pageSize = pageSize;
		},
		currentChange(current) {
			this.page.currentPage = current;
		},
		//未注册的设备查询
		queryUnRegisterDevList(val) {
			this.devData2 = [];
			getUnRegisterDevList({
				devModel: val,
			}).then((res) => {
				this.unDevData = res.data;
				for (let i = 0; i < res.data.length; i++) {
					this.devData2.push({
						key: res.data[i]?.unitNo,
						label: res.data[i]?.deviceName,
						disabled: false,
					});
				}
			});
		},
		//穿梭框过滤
		filterMethod(query, item) {
			return item.label?.indexOf(query) > -1;
		},
		//穿梭框批量保存
		save() {
			this.$refs.batchForm.validate((valid) => {
				if (valid) {
					let arr = [];
					if (this.batchData.length > 0) {
						this.batchData.forEach((item) => {
							let obj = this.unDevData.find((i) => i.unitNo == item);
							arr.push({
								unitNo: item,
								unitName: obj?.deviceName,
								devModel: obj?.productKey,
								remark: obj?.remark,
								energyType: this.batchForm.energyType,
								ratedPower: this.batchForm.ratedPower,
								devCategory: this.batchForm.devCategory,
							});
						});
					} else {
						this.$message.error('请选择设备');
						return;
					}
					batchAddDevList(arr)
						.then((data) => {
							this.$message.success('添加成功');
							this.showDialog = false;
							this.getList(this.page);
						})
						.catch(() => {
							loading();
						});
				}
			});
		},
		open(row) {
			this.batchData = [];
			this.showDialog = true;
			this.$refs.batchForm.resetFields();
		},
		searchFilter(data, done) {
			this.page.currentPage = 1;
			this.getList(this.page, data);
			done();
		},
		//初始化表格数据
		getList(page, params) {
			this.tableLoading = true;
			getDevList(
				Object.assign(
					{
						current: page.currentPage,
						size: page.pageSize,
					},
					params
				)
			).then((res) => {
				this.data = res.data.records;
				this.page.total = res.data.total;
				this.tableLoading = false;
			});
			this.queryUnRegisterDevList();
		},
		handleSave: function (row, done, loading) {
			row.unitNo = row.unitNo;
			addDevList([row])
				.then((res) => {
					if (res.data == false) {
						this.$message.error(res.msg);
					} else {
						this.$message.success('添加成功');
						done();
					}
					loading();
					this.refreshChange();
				})
				.catch((err) => {
					loading();
				});
		},
		handleUpdate: function (row, index, done, loading) {
			editDevList(row)
				.then(() => {
					this.$message.success('修改成功');
					this.refreshChange();
					done();
				})
				.catch(() => {
					done();
				});
		},
		rowDel: function (row, index) {
			this.$confirm('是否确认删除', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(function () {
					return delDevList([row.id]);
				})
				.then((data) => {
					this.$message.success('删除成功');
					this.getList(this.page);
				})
				.catch((cancelorerror) => {});
		},
		refreshChange() {
			this.getList(this.page);
		},
		handleOpenBefore(show, type) {
			if (type == 'edit') {
				this.editDisabled = true;
			} else {
				this.editDisabled = false;
			}
			show();
		},
	},
};
</script>
<style lang="scss" scoped>
:deep(.el-transfer-panel) {
	width: 40%;
}
</style>
